package com.fdb.basic.framework.core.spring;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.fdb.basic.framework.core.util.AESUtility;
import com.fdb.basic.framework.core.util.PropertiesUtil;
import com.fdb.basic.framework.core.util.RSAUtility;
import com.fdb.basic.framework.core.util.StringUtil;

/**
 * 
 * 配置属性加解密
 * 
 * @author Cytus_
 * @since 2018年6月25日 下午3:33:27
 * @version 1.0
 *
 */
public class DecryptPropteryPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    
    
    protected String convertProperty(String propertyName, String propertyValue) {
        try {
            if (isRasDecryptProperty(propertyName)) {
                propertyValue = super.convertProperty(propertyName, RSAUtility.decryptByBase64(propertyValue, PropertiesUtil.getPropertyByKey("key", "rsa.privateKey")));
            }
            
            if (isAesDecryptProperty(propertyName)) {
                propertyValue = super.convertProperty(propertyName, AESUtility.decryptMD5Key(propertyValue, PropertiesUtil.getPropertyByKey("key", "aes.key")));
            }
        } catch (Exception e) {
            LoggerFactory.getLogger(DecryptPropteryPlaceholderConfigurer.class).error(e.getMessage(), e);
        }
        return convertPropertyValue(propertyValue);
    }
    
    private boolean isRasDecryptProperty(String propertyName) {
        String cfgRasDecrypt = PropertiesUtil.getPropertyByKey("application", propertyName+ ".rsa.decrypt");
        return StringUtil.isNotEmpty(propertyName) && Boolean.valueOf(cfgRasDecrypt);
    }

    private boolean isAesDecryptProperty(String propertyName) {
        String cfgRasDecrypt = PropertiesUtil.getPropertyByKey("application", propertyName+ ".aes.decrypt");
        return StringUtil.isNotEmpty(propertyName) && Boolean.valueOf(cfgRasDecrypt);
    }
    
}
